#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <cstdlib>
#include <ctime>

//共享资源
int shared_data = 0;

//读写锁
pthread_rwlock_t rwlock;

//读者线程函数
void* Reader(void* args)
{
    //sleep(1);
    //读者优先， 读者进入 && 读者很多 写者很难进入了

    int number = *(int*)args;
    while(true)
    {
        //读者加锁
        pthread_rwlock_rdlock(&rwlock);
        std::cout << "读者-" << number << " 正在读取. 数据是 " << shared_data << std::endl;
        //模拟读取操作
        // sleep(1);
        //解锁
        pthread_rwlock_unlock(&rwlock);

         sleep(1);
    }

    delete (int*)args;
    return nullptr;
}

//写者线程函数
void* Writer(void* args)
{
    int number = *(int*)args;
    while(true)
    {
        //写者加锁
        pthread_rwlock_wrlock(&rwlock);
        //修改共享资源
        shared_data = rand() % 10;
        std::cout << "写者-" << number << " 正在写入. 新的数据是 " << shared_data << std::endl;
        //模拟写入操作
        sleep(2);
        //解锁
        pthread_rwlock_unlock(&rwlock);
    }

    delete (int*)args;
    return nullptr;
}

int main()
{
    srand(time(nullptr) ^ getpid());
    //初始化读写锁
    pthread_rwlock_init(&rwlock, nullptr);

    // 可以更高读写数量配比，观察现象
    const int reader_num = 2;
    const int writer_num = 2;
    const int total = reader_num + writer_num;
    pthread_t threads[total];
    //假设读者与写者数量相等

    //创建读者线程
    for(int i = 0;i < reader_num;i++)
    {
        int* id = new int(i);
        pthread_create(&threads[i], NULL,Reader, id);
    }

    //创建写者线程
    for (int i = reader_num; i < total; ++i)
    {
        int *id = new int(i - reader_num);
        pthread_create(&threads[i], NULL, Writer, id);
    }

    //等待所有线程结束
    for(int i = 0;i < total;i++)
    {
        pthread_join(threads[i], nullptr);
    }

    //销毁读写锁
    pthread_rwlock_destroy(&rwlock);

    return 0;
}